package server

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/const"
	time2 "longmen/server/pkg/common/helper/timehelper"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/db_guess"
	"longmen/server/pkg/db/mysql/db_live"
	"longmen/server/pkg/db/mysql/models/models_guess"
	"longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
	"time"
)

func (s *Server) CreateGuessOrder(ctx context.Context, req *pb.CreateGuessOrderReq) (*pb.CreateGuessOrderResp, error) {
	gorder := &models_guess.GuessOrder{
		CreateTime: time.Now(),
		GuessId:    int(req.GId),
		GuessItem:  int(req.GuessItem),
		AnchorId:   int(req.AnchorId),
		Uid:        int(req.Uid),
		LiveId:     req.LiveId,
		Amount:     int(req.Amount),
		Status:     _const.GUESS_ORDER_INIT,
	}
	if req.LiveId == 0 {
		return nil, errors.New(_const.GUESS_ERR_BAD_LIVE_ID)
	}
	oLive, err := db_live.GetLiveParam(map[string]interface{}{"liveid": req.LiveId})

	if err != nil || oLive.Liveid == 0 {
		return nil, errors.New(_const.GUESS_ERR_BAD_LIVE_ID)
	}
	if oLive.Anchorid == int(req.Uid) {
		return nil, errors.New(_const.GUESS_ERR_SELF_BET)
	}
	id, gInfo, err := cache.AddGuessOrder(gorder) //尝试下单，效验放在cache里
	if err != nil {
		return nil, err
	}
	gorder.CategoryId = gInfo.CategoryId
	global.Log.Infof("下单成功:%+v", gorder)
	cache.DelUserFullCache(gorder.Uid)
	err = cache.PrepareMsgUpdateGuessStatus(gorder.LiveId, false)
	if err != nil {
		global.Log.Errorf("create models_guess order:%s", err.Error())
	}
	return &pb.CreateGuessOrderResp{
		UserProftId: int32(id),
		Msg:         "ok",
	}, nil
}
func (s *Server) GetGuessOrder(ctx context.Context, req *pb.GetGuessOrderReq) (*pb.GetGuessOrderResp, error) {
	var err error
	o := &models_guess.GuessOrder{}
	mQuery := make(map[string]interface{}, 0)

	if req.AnchorId > 0 {
		(mQuery)["anchor_id"] = req.AnchorId
	}
	if req.Uid > 0 {
		(mQuery)["uid"] = req.Uid
	}
	if req.GorderId > 0 {
		(mQuery)["id"] = req.GorderId
	}

	if len(mQuery) == 0 {
		return nil, fmt.Errorf("参数有误")
	}

	err = db_guess.GetGuessAnyParam(o, mQuery, true, "GetGOList")
	if err != nil {
		return nil, err
	}
	return &pb.GetGuessOrderResp{
		Id:         int32(o.Id),
		GId:        int32(o.GuessId),
		GuessItem:  int32(o.GuessItem),
		AnchorId:   int32(o.AnchorId),
		LiveId:     int32(o.LiveId),
		CategoryId: int32(o.CategoryId),
		Uid:        int32(o.Uid),
		Status:     int32(o.Status),
		Profit:     int32(o.Profit),
		CreateTime: o.CreateTime.Format("2006-01-02 15:04:05"),
	}, nil

}
func (s *Server) GetGuessOrderList(ctx context.Context, req *pb.GetGuessOrderListReq) (*pb.GetGuessOrderListResp, error) {
	var err error
	var n int64
	oGOList := make([]*models_guess.GuessOrder, 0, 0)
	mQuery := make(map[string]interface{}, 0)

	if req.AnchorId > 0 {
		(mQuery)["anchor_id"] = req.AnchorId
	}
	if req.Uid > 0 {
		(mQuery)["uid"] = req.Uid
	}
	if req.Status > 0 {
		(mQuery)["status"] = req.Status
	}
	if req.LiveId > 0 {
		(mQuery)["live_id"] = req.LiveId
	}
	if len(req.TEnd) != 0 && len(req.TStart) > 0 {
		if time2.StrToUnix(req.TEnd) == 0 {
			return nil, fmt.Errorf("时间格式有误")
		}
		if time2.StrToUnix(req.TStart) == 0 {
			return nil, fmt.Errorf("时间格式有误")
		}
		mQuery["create_time"] = map[string]interface{}{"between": []interface{}{req.TStart, req.TEnd}}
	}

	if len(mQuery) == 0 {
		return nil, fmt.Errorf("参数有误")
	}

	err = mysql.GetXAnyListParam(&models_guess.GuessOrder{}, &oGOList, mQuery, "GetGOList", "create_time DESC", int(req.Page), int(req.Size))
	if err != nil {
		return nil, err
	}
	err = mysql.CountXAnyParam(&models_guess.GuessOrder{}, &n, mQuery, "GetGOListCount", "", "", 0, 0)
	if err != nil {
		return nil, err
	}

	slice := make([]*pb.GetGuessOrderResp, 0)
	for _, v := range oGOList {
		if v.Id > 0 {
			anchorName, _ := cache.GetAnchorNameById(v.AnchorId)
			oGuess, _ := cache.GetGuessInfo(v.GuessId, 0, false)
			if oGuess == nil {
				continue
			}
			sOddsList, _ := json.Marshal(oGuess.OddsList)
			slice = append(slice, &pb.GetGuessOrderResp{
				Id:        int32(v.Id),
				GId:       int32(v.GuessId),
				GuessItem: int32(v.GuessItem),
				AnchorId:  int32(v.AnchorId),
				LiveId:    int32(v.LiveId),

				Uid:        int32(v.Uid),
				Amount:     int32(v.Amount),
				CategoryId: int32(v.CategoryId),
				Status:     int32(v.Status),
				Profit:     int32(v.Profit),
				PayStatus:  int32(v.PayStatus),
				CreateTime: v.CreateTime.Format("2006-01-02 15:04:05"),
				AnchorName: anchorName,
				Guess: &pb.GetGuessResp{
					GId: int32(oGuess.GId),
					QId: int32(oGuess.QId),

					Status:  int32(oGuess.Status),
					ItemNum: int32(oGuess.ItemNum),
					Odds:    string(sOddsList),

					MatchTitle: oGuess.MatchTitle,
					LiveTitle:  oGuess.LiveTitle,
					Title:      oGuess.Title,
					Content:    oGuess.Content,
					Comp:       oGuess.Comp,
					Result:     int32(oGuess.Result)},
			})
		}
	}
	return &pb.GetGuessOrderListResp{
		Total:      n,
		GuessOrder: slice,
	}, nil

}
